<?php


namespace app\admin\services;


use app\admin\controller\SkuCategory;
use app\admin\model\ClassifyModel;
use app\admin\model\SkuCategoryModel;
use app\admin\model\SkuCategoryValueModel;
use app\admin\model\SkuMoldModel;
use think\facade\Validate;

class ClassifyService extends BaseService
{
    /**
     * 递归子树，废弃
     * @param $p
     * @return void
     */
    public static function recursionList($p = [])
    {
        $p = [
            'where' => [],
            'page' => 'all',
            'order' => 'level desc'
        ];
        if (!empty($p['type']))
            $p['where'][] = ['type', '=', $p['type']];
        $list = ClassifyModel::getList($p)->toArray();
        $list = array_column($list, null, 'id');
        foreach ($list as $key => $item) {
            if ($item['parent']) {
                $list[$item['parent']]['children'][] = $list[$key];
                unset($list[$key]);
            }
        }
        api_return(200, '', ['list' => array_values($list)]);
    }

    /**
     * 数据列表
     * @param $p get请求参数
     * @return void
     */
    public static function tableList($p)
    {

        $params = [
            'where' => [],
            'page' => ($p['pageNo']) ?? 1,
            'pageSize' => ($p['pageSize']) ?? 10,
            'with' => [
                'creatUser' => function ($query) {
                    $query->withField(['id', 'nickname'])->withDefault(['id' => '', 'nickname' => '用户已移除']);
                },
                'skuMold' => function ($query) {
                    $query->withField(['id', 'name']);
                }
            ],
            'field' => '*'
        ];
        if (empty($p['page'])) {
//            $params['where'][]=[
//                ['category_sec_id','not in',[17,18]]
//            ];
        }
        if (!empty($p['type'])) {
            $params['where'][] = self::jsonConditionSelect('sku_mold_id', [$p['type']]);
        }
        if (!empty($p['code']))
            $params['where'][] = ['code', 'like', '%' . $p['code'] . '%'];
        if (!empty($p['label']))
            $params['where'][] = ['label|attribute_spec_label', 'like', '%' . $p['label'] . '%'];
        if (!empty($p['keyword']))
            $params['where'][] = ['label|attribute_spec_label|code', 'like', '%' . $p['keyword'] . '%'];
        $list = ClassifyModel::getList($params);
        $objectList = SkuCategoryValueModel::column('name,object', 'id');
        foreach ($list as $item) {
            $item['creator_nickname'] = $item->creatUser->nickname;
            $item['classify_id'] = $item->id;
            unset($item->creatUser);
            $item['by_name'] = $item->code . '-' . $item->attribute_spec_label . '-' . $item->label;
            $item['attribute_name'] = self::buildNewAttributeObject($item['attribute_name'], $objectList);
            $item['attribute_spec'] = self::buildNewAttributeObject($item['attribute_spec'], $objectList);

        }
        $count = ClassifyModel::count($params['where']);
        api_return(200, '', ['list' => $list, 'total' => $count]);
    }

    public static function edit($p)
    {

        $rule = [
//            'sku_mold_id'=>'require',
//            'attribute_name'=>'require',
//            'attribute_spec'=>'require',
            'attribute_name_label' => 'require',
            'attribute_spec_label' => 'require',
//            'type'=>'require|in:A,B,C',
//            'measure_unit'=>'require|in:1,2,3,4',
            'mold_id' => 'require'
        ];
        $validate = \think\facade\Validate::rule($rule);
        if (!$validate->check($p))
            api_return(500, $validate->getError());
        if (!empty($p['tempPath']) && !empty($p['fileType'])) {
            $p['pic_path'] = self::getUploadField($p['tempPath'], $p['fileType'], $p['temp_old']);
        }
        if (!empty($p['tempPath_file']) && !empty($p['fileType_file'])) {
            $p['file_path'] = self::getUploadField($p['tempPath_file'], $p['fileType_file'], $p['temp_old_file']);
        }
        $p['label'] = $p['attribute_name_label'];
        self::multDuplicateCheck('label',$p,'attribute_spec_label');
        ClassifyModel::edit($p);
    }

    public static function del($p)
    {
        $rule = ['ids' => 'require'];
        $validate = \think\facade\Validate::rule($rule);
        if (!$validate->check($p))
            api_return(500, $validate->getError());
        $params = [
            'where' => [['id', 'in', $p['ids']]],
            'page' => 'all'
        ];
        $list = ClassifyModel::getList($params);
        foreach ($list as $item) {
            if (!empty($item->stock))
                api_return(500, '当前分类库存尚余,请先删除库存分类');
            if (!empty($item->project_classify) && count($item->projectClassify)) {
                api_return(500, '当前分类项目尚余,请先清空项目分类', $list);
            }
        }
        ClassifyModel::delByIds($p['ids']);

    }

    /**
     * 创建SKU编码 （废弃）
     * @param $skuInfo sku相信信息
     * @return string
     */
//    public static function createSkuCode($skuInfo){
//        $codeList=[];
//        foreach ($skuInfo['category_value'] as $item){
//            if(!empty($item['object']['options'])){
//                $labeList=array_column($item['object']['options'],'code','label');
//                $codeList[$item['name']]=($labeList[$item['value']])??'';
//            }
//            if($item['name']=='生产日期'){
//                $codeList[$item['name']]=self::getPDCode($item['value']);
//            }
//
//        }
//        $code=[
//            'x1x2x3'=>empty($codeList['品牌'])?'ZZZ':substr($codeList['品牌'],0,3),
//            'x4'=>substr(SkuCategoryModel::find($skuInfo['category_id'])['code'],0,1),
//            'x5'=>substr(SkuCategoryModel::find($skuInfo['category_sec_id'])['code'],0,1),
//            'x6x7x8'=>empty($codeList['外观'])?'ZZZ':substr($codeList['外观'],0,3),
//            'x9x10x11'=>empty($codeList['容量'])?'ZZZ':substr($codeList['容量'],0,3),
//            'x12x13x14'=>empty($codeList['生产日期'])?"ZZZ":$codeList['生产日期'],
//            'x15'=>empty($codeList['状态'])?'Z':substr($codeList['状态'],0,1),
//            'x16'=>substr(SkuMoldModel::find($skuInfo['sku_mold_id'])['code'],0,1),
//        ];
//        return implode('',$code);
//    }

    /**
     * 获取生产日期编码
     * @param $date 生产日期
     * @return string 按格式返回生产日期编码
     */
    protected static function getPDCode($date)
    {
        $timeList = explode('-', date('Y-m-d', strtotime($date)));
        $yearList = [
            '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
            'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N',
            'P', 'R', 'S', 'T', 'V', 'W', 'X', 'Y'
        ];
        $dayList = [
            '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
            'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N',
            'P', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', '0'
        ];
        $code = [
            $yearList[$timeList[0] % 2011],
            dechex($timeList[1]),
            $dayList[$timeList[2] - 1]
        ];
        return implode('', $code);
    }

    /**
     * sku复制
     * @param $p
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function copy($p)
    {
        $rule = [
            'id' => 'require',
            'type' => 'require|in:A,B,C'
        ];
        $validate = Validate::rule($rule);
        if (!$validate->check($p)) {
            api_return(500, $validate->getError());
        }
        if ($res = ClassifyModel::find($p['id'])->toArray()) {
            $res['code'] = $p['type'] . substr($res['code'], 1);
            $res['attribute_name_label'] = $res['label'] = str_replace('/' . $res['type'] . '/', '/' . $p['type'] . '/', $res['label']);
            $res['type'] = $p['type'];
            unset($res['id']);
            ClassifyModel::duplicateCheck('code', $res);
            ClassifyModel::edit($res);
        } else {
            api_return(500, '数据不存在');
        }
    }

    protected static function buildNewAttributeObject($content, $objectList)
    {
        $newArray = [];
        foreach ($content as $item) {
            $newArray[] = [
                'id' => $item['id'],
                'name' => ($objectList[$item['id']]['name']) ?? '已删除',
                'object' => (($objectList[$item['id']]['object'])) ?? '已删除',
                'input_type' => $item['input_type'],
                'value' => ($item['value']) ?? '',
            ];
        }
        return $newArray;
    }

    /**
     * 数据列表
     * @param $p get请求参数
     * @return void
     */
    public static function all($p)
    {

        $params = [
            'where' => [],
            'page' => ($p['pageNo']) ?? 1,
            'pageSize' => ($p['pageSize']) ?? 10,
            'field' => 'id,label,mold_id'
        ];
        if (empty($p['page'])) {
//            $params['where'][]=[
//                ['category_sec_id','not in',[17,18]]
//            ];
        }
        if (!empty($p['type'])) {
            $params['where'][] = self::jsonConditionSelect('sku_mold_id', [$p['type']]);
        }
        if (!empty($p['code']))
            $params['where'][] = ['code', 'like', '%' . $p['code'] . '%'];
        if (!empty($p['label']))
            $params['where'][] = ['label|attribute_spec_label', 'like', '%' . $p['label'] . '%'];
        if (!empty($p['keyword']))
            $params['where'][] = ['label|attribute_spec_label|code', 'like', '%' . $p['keyword'] . '%'];
        $list = ClassifyModel::getList($params);
        api_return(200, '', ['list' => $list]);
    }

    public static function attr($p)
    {

        $params = [
            'where' => [],
            'page' => ($p['pageNo']) ?? 1,
            'pageSize' => ($p['pageSize']) ?? 10,
            'field' => 'id,label,attribute_name,attribute_spec'
        ];
        $list = ClassifyModel::getList($params);
        $objectList = SkuCategoryValueModel::column('name,object', 'id');
        foreach ($list as $item) {
            $item['attribute_name'] = self::buildNewAttributeObject($item['attribute_name'], $objectList);
            $item['attribute_spec'] = self::buildNewAttributeObject($item['attribute_spec'], $objectList);

        }
        api_return(200, '', ['list' => $list]);
    }

    public static function multDuplicateCheck($field, $data, $field2)
    {
        if (!empty($data['id'])) {
            $res = ClassifyModel::where([
                    ['id', '<>', $data['id']],
                    [$field, '=', $data[$field]],
                    [$field2, '=', $data[$field2]]
                ]
            )->find();
        } else {
            $res = ClassifyModel::where([
                [$field, '=', $data[$field]],
                [$field2, '=', $data[$field2]]
            ])->find();
        }
        if ($res)
            api_return(500, '名称规格重复');
    }
}
